"""
算分核心
"""


class CalcCore:
    def __init__(self, base_input, user_input, sync_strategy, strategy):
        self.sync_strategy = sync_strategy # 时间同步时所使用的算法
        self.strategy = strategy # 默认算法
        print("开始视频同步算法")
        base_input_index, user_input_index = self.sync_time(base_input, user_input)  # 输出同步起始index

        self.base_input = base_input
        self.user_input = user_input
        self.base_input_index = base_input_index
        self.user_input_index = user_input_index

    def sync_time(self, base_input, user_input, interval=720, sep=5):  # 每次挪动10帧 计算一次分数 取分数最大的作为时间对齐线
        score_list = []
        base_input_frame_count = len(base_input)
        user_input_frame_count = len(user_input)
        for i in range(0, min(int(interval / 2), len(base_input)), sep):
            score = self._calc_score(strategy=self.sync_strategy, base_input=base_input, user_input=user_input,
                                     base_input_index=i, user_input_index=0,
                                     frame_num=min(interval, base_input_frame_count - i, user_input_frame_count))
            score_list.append((i, 0, score,))

        for j in range(0, min(int(interval / 2), len(user_input)), sep):
            score = self._calc_score(strategy=self.sync_strategy, base_input=base_input, user_input=user_input,
                                     base_input_index=0, user_input_index=j,
                                     frame_num=min(interval, base_input_frame_count, user_input_frame_count - j))
            score_list.append((0, j, score,))
        result_list = sorted(score_list, key=lambda x: x[2], reverse=False)
        print("计算引擎准备完成，时间轴自动同步为({},{})(注意：单位为帧数，mmpose默认帧率约为24帧每秒)".format(result_list[0][0], result_list[0][1]))
        print("开始执行计算，base_video开始帧为:{},user_video开始帧为:{}".format(self.base_input_index,
                                                                              self.user_input_index))
        return result_list[0][0], result_list[0][1]

    def _calc_score(self, strategy, base_input, user_input, base_input_index, user_input_index, frame_num):
        return strategy(base_input, user_input, base_input_index, user_input_index, frame_num)

    def calc_score(self, strategy):
        if strategy is None:
            strategy = self.strategy
        frame_num = min(len(self.base_input) - self.base_input_index, len(self.user_input) - self.user_input_index)
        return self._calc_score(strategy, self.base_input, self.user_input, self.base_input_index,
                                self.user_input_index, frame_num) / frame_num

